package com.thb.user.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;

import com.thb.exception.CommonExceptionHandler;
import com.thb.logs.utils.LogUtils;
import com.thb.utils.SpringContextUtils;

public class UserTokenFilter implements Filter {
	
	private static final Logger access = LogUtils.getAccessLog(); 

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
			HttpServletRequest re = (HttpServletRequest)request;
			HttpServletResponse ponse = (HttpServletResponse)response;
		
		try {
			
			String sid = request.getParameter("sid");
			
//			Object user = MemcachedUtil.get(MKeyUtils.getSidUserKey(sid));
			
			String ip = ((HttpServletRequest)request).getHeader("X-Real-IP");
			
			access.info(String.format("sid:[%s],ip:[%s],URI:[%s]",sid,ip,re.getRequestURI()));
			
			String uri = re.getRequestURI();
			
			if(uri.indexOf("posters/") != -1 ||  
					uri.indexOf("/user/register") != -1 ||
					uri.indexOf("/user/login") != -1||
					uri.indexOf("/user/updateForgetPasswd") != -1 ||
					uri.indexOf("/user/forgetPasswd") != -1 ||
					uri.indexOf("/version") != -1 ||
					uri.indexOf("/shares") != -1
					
					){
				chain.doFilter(request, response);
			}else{
				
				//判断是否登录超时
//				String userString = MemcachedSession.getSessionUsercode(sid);
//				if(userString == null){
//					throw new ServiceException("10", "当前登录已超时");
//				}
				
				//判断是否被踢下线
				
				
				chain.doFilter(request, response);
			}
		} catch (Exception e) {
			CommonExceptionHandler handler = (CommonExceptionHandler)SpringContextUtils.getBean("commonExceptionHandler");
			handler.resolveException(re, ponse, null, e);
		}
		
		
	}

	@Override
	public void destroy() {
		
	}

}
